package com.filters;

import com.common.util.rsa.RsaKeys;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.service.RsaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.InputStream;
import java.nio.charset.Charset;

@Component
public class RSAResponseFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(RSAResponseFilter.class);
    
    @Autowired
	private RsaService rsaService;
    
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
    	//这里一定要将顺序设置在zuul默认的response filter之前，否则没有效果
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        
        return true;
    }

    @Override
    public Object run() {
    	
    	try {
            RequestContext context = RequestContext.getCurrentContext();
            InputStream stream = context.getResponseDataStream();
            String responseBody = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
            System.out.println("原始的response body: " + responseBody);
            
            //加密返回的数据
            String encryptResponseBody = rsaService.RSAEncryptDataPEM(responseBody, RsaKeys.getAppPubKey());
            System.out.println("加密后的response body: " + encryptResponseBody);
            context.setResponseBody("encrypt data: " + encryptResponseBody);
            
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }
}